/*
 * Filename:  UsmcApp.java
 * Copyright:  Raisecom Technologies Co., Ltd. Copyright YYYY-YYYY,  All rights reserved
 * Description:  <description>
 * Author:  donghu
 * Edit-time:  2016-5-4
 * Modify content:  <modify content>
 */
package com.gutetec.cms.usmc;

import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
import io.dropwizard.configuration.SubstitutingSourceProvider;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.hibernate.HibernateBundle;
import io.dropwizard.migrations.MigrationsBundle;
import io.dropwizard.server.SimpleServerFactory;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

import javax.servlet.DispatcherType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.gutetec.cms.usmc.cometdclient.RocCometdClient;
import com.gutetec.cms.usmc.db.util.UsmcDBUtil;
import com.gutetec.cms.usmc.db.util.UsmcDbMapper;
import com.gutetec.cms.usmc.resource.SafeResource;
import com.gutetec.cms.usmc.resource.UserResource;

/**
 * 
 * <main class of usmc>
 * <Function details>
 * @author  donghu
 * @version  [Version, 2016-5-4]
 * @see  [Classs/Method]
 * @since  [Product/Model Version]
 */
public class UsmcApp extends Application<UsmcAppConfig>
{
    
    private static final Logger LOGGER = LoggerFactory.getLogger(UsmcApp.class);
    
    public static void main(String[] args)
        throws Exception
    {
        new UsmcApp().run(args);
    }
    
    HibernateBundle<UsmcAppConfig> hibernateBundle;
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize(Bootstrap<UsmcAppConfig> bootstrap)
    {
        bootstrap.addBundle(new AssetsBundle("/api-doc", "/api-doc", "index.html", "api-doc"));
        //bootstrap.addBundle(new AssetsBundle("/uiframe", "/iui/uiframe", "index.html", "iui-uiframe"));
        /*bootstrap.setConfigurationSourceProvider(new SubstitutingSourceProvider(
        		bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false)));*/
        
        bootstrap.addBundle(new MigrationsBundle<UsmcAppConfig>()
        {
            @Override
            public DataSourceFactory getDataSourceFactory(UsmcAppConfig configuration)
            {
                return configuration.getDataSourceFactory();
            }
        });
        
        List<Class<?>> sfEntitysList = initSfEntityClass();
        hibernateBundle = new HibernateBundle<UsmcAppConfig>(UsmcApp.class,
            sfEntitysList.toArray(new Class<?>[sfEntitysList.size()]))
        {
            @Override
            public DataSourceFactory getDataSourceFactory(UsmcAppConfig configuration)
            {
                return configuration.getDataSourceFactory();
            }
        };
        
        bootstrap.addBundle(hibernateBundle);
    }
    
    @Override
    public void run(UsmcAppConfig umcAppConfig, Environment environment)
    {
        
        //Cross domain
        environment.getApplicationContext().addFilter(
            org.eclipse.jetty.servlets.CrossOriginFilter.class, "/api/v1/*",
            EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));
        
        // register resource
        environment.jersey().register(new ApiListingResource());
        environment.jersey().register(new SafeResource());
        environment.jersey().register(new UserResource());
        
        //set hibernate session
        UsmcDBUtil.setSessionFactory(hibernateBundle.getSessionFactory());
        
        environment.getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
        
        //RocCometdClient.getInstance().subscribe(umcAppConfig.getRocServerAddr());
        
        //set swagger
        BeanConfig config = new BeanConfig();
        config.setTitle("USMC Services");
        config.setVersion("1.0.0");
        config.setResourcePackage("com.raisecom.itms.usmc");
        SimpleServerFactory simpleServerFactory = (SimpleServerFactory)umcAppConfig.getServerFactory();
        String basePath = simpleServerFactory.getApplicationContextPath();
        String rootPath = simpleServerFactory.getJerseyRootPath();
        rootPath = rootPath.substring(0, rootPath.indexOf("/*"));
        basePath = basePath.equals("/") ? rootPath : (new StringBuilder()).append(basePath).append(rootPath).toString();
        config.setBasePath(basePath);
        config.setScan(true);
    }
    
    @Override
    public String getName()
    {
        return " USMC APP ";
    }
    
    /**
     * collect all hibernate entity classes for HibernateBundle.
     * 
     */
    private List<Class<?>> initSfEntityClass()
    {
        List<Class<?>> sfEntitysList = new ArrayList<Class<?>>();
        
        sfEntitysList.addAll(UsmcDbMapper.getSafeEntityClasses());
        
        return sfEntitysList;
    }
}
